package demo2;

import java.util.Scanner;

public class LongestCommonSubsequence {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // 获取用户输入
        System.out.print("请输入第一个序列 X: ");
        String X = scanner.nextLine();
        System.out.print("请输入第二个序列 Y: ");
        String Y = scanner.nextLine();

        // 调用方法并输出结果
        String lcs = findLCS(X, Y);
        System.out.println("最长公共子序列: " + lcs);

        scanner.close();
    }

    public static String findLCS(String X, String Y) {
        int m = X.length();
        int n = Y.length();

        // 用字符串数组存子序列
        String[][] table = new String[m + 1][n + 1];

        // 初始化空字符串
        for (int i = 0; i <= m; i++) {
            for (int j = 0; j <= n; j++) {
                table[i][j] = "";
            }
        }

        // 填表
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (X.charAt(i - 1) == Y.charAt(j - 1)) {
                    table[i][j] = table[i - 1][j - 1] + X.charAt(i - 1);
                } else {
                    table[i][j] = table[i - 1][j].length() > table[i][j - 1].length()
                            ? table[i - 1][j] : table[i][j - 1];
                }
            }
        }

        return table[m][n];  // 直接返回右下角的字符串
    }
}